FGS.HTMLParser = function (aHTMLString)
{
	var html = document.implementation.createDocument("http://www.w3.org/1999/xhtml", "html", null),
	body = document.createElementNS("http://www.w3.org/1999/xhtml", "body");
	html.documentElement.appendChild(body);
	
		
	aHTMLString = aHTMLString.replace(/ src=\"/gi, ' longdesc="');
	aHTMLString = aHTMLString.replace(/ src=\'/gi, " longdesc='");
	

	body.appendChild(Components.classes["@mozilla.org/feed-unescapehtml;1"]
		.getService(Components.interfaces.nsIScriptableUnescapeHTML)
		.parseFragment(aHTMLString, false, null, body));
	
	return html;
};

FGS.GetCookieToken = function(params, callback)
{
	var ios = Components.classes["@mozilla.org/network/io-service;1"]
			.getService(Components.interfaces.nsIIOService);
	var uri = ios.newURI(params.cookieToGet.url, null, null);
	
	var cookieSvc = Components.classes["@mozilla.org/cookieService;1"]
			.getService(Components.interfaces.nsICookieService);
	var cookie = cookieSvc.getCookieString(uri, null);
	
	
	FGS.jQuery.each(cookie.split(/; */), function(k, cookieString)
	{
		var splitCookie = cookieString.split('=');
		
		if(splitCookie[0] == params.cookieToGet.name)
		{
			params.cookieValue = splitCookie[1];
			callback(params);
			return false;
		}
	});	
};

FGS.copyLink = function(msg)
{
	try
	{
		var str = Components.classes["@mozilla.org/supports-string;1"].
            createInstance(Components.interfaces.nsISupportsString);
		if (!str) return false;
		str.data = msg;

		var trans = Components.classes["@mozilla.org/widget/transferable;1"].
              createInstance(Components.interfaces.nsITransferable);
		if (!trans) return false;


		trans.addDataFlavor("text/unicode");
		trans.setTransferData("text/unicode",str,msg.length * 2);

		var clipid = Components.interfaces.nsIClipboard;
		var clip = Components.classes["@mozilla.org/widget/clipboard;1"].getService(clipid);
		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);
		return true;
	}
	catch(e)
	{
		return false;
	}
};
	
FGS.openURI = function(url, background)
{
	if(typeof(background) == 'undefined')
	{
		var background = true;
	}
	
	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	while (browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);
			if (url == b.currentURI.spec)
			{
				return false;
			}
		}
	}
	gBrowser.addTab(url, {inBackground: background});
};

FGS.hideFromFeed = function(bonusID, limit)
{
	var stmt = FGS.database.db.createStatement("SELECT * FROM bonuses where id = :id");
	stmt.params.id = bonusID;
	
	stmt.executeAsync({
		handleResult: function(aResultSet)
		{

			for (var row = aResultSet.getNextRow();	 row;	 row = aResultSet.getNextRow()) 
			{

				var v =
				{
					gameID: row.getResultByName("gameID"),
					feedback: row.getResultByName("feedback"),
					link_data: row.getResultByName("link_data"),
				}
				
				if(limit)
				{
					if(!FGS.options.games[v.gameID].hideFromFeedLimitError)
					{	
						return;
					}
				}
				else
				{
					if(!FGS.options.games[v.gameID].hideFromFeed)
					{	
						return;
					}
				}
				
					
				var tmpObj = JSON.parse(v.feedback);
				
				if(typeof tmpObj.target_profile_id == 'undefined')
					tmpObj.target_profile_id = tmpObj.actor;
				
				
				var postData = { 
					'action': 'uninteresting',
					'post_form_id': FGS.post_form_id,
					'fb_dtsg':	FGS.fb_dtsg,
					'object_ids[0]': tmpObj.target_profile_id,
					'object_ids[1]': tmpObj.source_app_id,
					'story_fbids[0]': tmpObj.target_profile_id+':'+tmpObj.target_fbid,
					'source': 'home',
					'nctr[_mod]': 'pagelet_home_stream',
					'lsd':	'',
					'post_form_id_source':'AsyncRequest',
					'lazy': 1,
					'stale_ok': 1
				};

				var postData = FGS.jQuery.param(postData).replace(/%5B/g,'[').replace(/%5D/g,']');
				
				var obj = {
					arguments:
					{
						'type': 'POST',
						'url': 'https://www.facebook.com/ajax/feed/filter_action.php?__a=1',
						'data': postData
					},
					params: []
				};
				
				FGSoperator.postMessage(obj);

			}
		},
		handleError: function(aError) {},
		handleCompletion: function(aReason)	{}
	});
};

FGS.commentBonus = function(bonusID, comment)
{
	var stmt = FGS.database.db.createStatement("SELECT * FROM bonuses where id = :id");
	stmt.params.id = bonusID;
	
	stmt.executeAsync({
		handleResult: function(aResultSet)
		{
			for (var row = aResultSet.getNextRow();	 row;	 row = aResultSet.getNextRow()) 
			{
				var v =
				{
					gameID: row.getResultByName("gameID"),
					feedback: row.getResultByName("feedback"),
					link_data: row.getResultByName("link_data"),
				}

				var postData = { 
					'charset_test': FGS.charset_test,
					'post_form_id': FGS.post_form_id,
					'fb_dtsg':	FGS.fb_dtsg,
					'xhp_ufi': 1,
					'comment': 'Add comment',
					'feedback_params': v.feedback,
					'add_comment_text': comment,
					'link_data': v.link_data,
					'nctr[_mod]': 'pagelet_home_stream',
					'lsd':	'',
					'post_form_id_source':'AsyncRequest',
					'lazy': 1,
					'stale_ok': 1	
				};

				var postData = FGS.jQuery.param(postData).replace(/%5B/g,'[').replace(/%5D/g,']');
			
				var obj = {
					arguments:
					{
						'type': 'POST',
						'url': 'https://www.facebook.com/ajax/ufi/modify.php?__a=1',
						'data': postData
					},
					params: [bonusID, 'comment'],
					callback: 'FGS.commentOrLikeBonus_callback'
				};
				
				FGSoperator.postMessage(obj);
			}
		},
		handleError: function(aError) {},
		handleCompletion: function(aReason)	{}
	});
};

FGS.likeBonus = function(bonusID, autolike)
{
	var stmt = FGS.database.db.createStatement("SELECT * FROM bonuses where id = :id");
	stmt.params.id = bonusID;
	
	stmt.executeAsync({
		handleResult: function(aResultSet)
		{
			for (var row = aResultSet.getNextRow();	 row;	 row = aResultSet.getNextRow()) 
			{
				var v =
				{
					gameID: row.getResultByName("gameID"),
					feedback: row.getResultByName("feedback"),
					link_data: row.getResultByName("link_data"),
				}
				
				if(typeof(autolike) != 'undefined')
				{
					if(!FGS.options.games[v.gameID].likeBonus)
					{	
						return;
					}
				}

				var postData = {
					'charset_test': FGS.charset_test,
					'post_form_id': FGS.post_form_id,
					'fb_dtsg':	FGS.fb_dtsg,
					'xhp_ufi': 1,
					'like': '',
					'feedback_params': v.feedback,
					'add_comment_text': '',
					'link_data': v.link_data,
					'nctr[_mod]': 'pagelet_home_stream',
					'lsd':	'',
					'post_form_id_source':'AsyncRequest',
					'lazy': 1,
					'stale_ok': 1
				};

				var postData = FGS.jQuery.param(postData).replace(/%5B/g,'[').replace(/%5D/g,']');
			
				var obj = {
					arguments:
					{
						'type': 'POST',
						'url': 'https://www.facebook.com/ajax/ufi/modify.php?__a=1',
						'data': postData
					},
					params: [bonusID, 'like'],
					callback: 'FGS.commentOrLikeBonus_callback'
				};
				
				FGSoperator.postMessage(obj);
			}
		},
		handleError: function(aError) {},
		handleCompletion: function(aReason)	{}
	});
};

FGS.sendbackGift = function (bonusID, sendbackData)
{
	var stmt = FGS.database.db.createStatement("SELECT * FROM requests where id = :id");
	stmt.params.id = bonusID;
	
	stmt.executeAsync({
		handleResult: function(aResultSet)
		{
			for (var row = aResultSet.getNextRow();	 row;	 row = aResultSet.getNextRow()) 
			{
				var v =	{	gameID: row.getResultByName("gameID"), post: row.getResultByName("post")	}
				
				if(!FGS.options.games[v.gameID].sendbackGift)
				{	
					return;
				}
				
				var gameID = v.gameID;			
				
				FGS.sendView('changeSendbackState', bonusID);
				
				var tempData = sendbackData;
				
				if(typeof tempData.destInt == 'undefined' || tempData.destInt == '')
				{
					var postData = v.post;
					tempData.destInt = FGS.Gup('params\\\[from_id\\\]', postData);
				}
				
				var params = {
					gift: tempData.gift,
					gameID:	gameID,
					sendTo: [tempData.destInt],
					sendToName: tempData.destName,
					thankYou: true,
					bonusID: bonusID,	
					isRequest: true
				};
				
				var game = FGS.gamesData[gameID].systemName;
				
				FGS[game].Freegifts.Click(params);
			}
		},
		handleError: function(aError) {},
		handleCompletion: function(aReason)	{}
	});
};



FGS.sendView = function(msg, data, data2, data3)
{
	if(msg == 'requestError' || msg == 'requestSuccess' || msg == 'bonusError' || msg == 'bonusSuccess')
	{
		if(data == FGS.xhrFarmWorking)
		{
			FGS.xhrFarmWorking = 0;
		}
		else
		{
			FGS.xhrWorking--;
		}
	}

	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	var found = false;
	var view = null;
	
	var tmpUrl = 'chrome://fgs/content/giftlist.html';
	
	while (!found && browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);				
			if (tmpUrl == b.currentURI.spec)
			{
				view = b.contentWindow;
				found = true;
				break;
			}
		}
	}	
	
	if(found)
	{
		if(msg == 'close')
		{
			view.close();
		}
		else if(msg == 'closeAndOpen')
		{
			view.close();
			FGS.saveOptions(FGS.startup);
		}
		
		else if(msg == 'friendsLoaded')
		{
			view.friendsLoaded(data, data2);
		}
		
		else if(msg == 'changeSendbackState')
		{
			view.changeSendbackState(data);
		}

		// bonusy //
		else if(msg == 'bonusError')
		{
			if(data2.error == 'limit')
			{
				FGS.hideFromFeed(data, true);
			}
			view.bonusError(data, data2);
		}
		else if(msg == 'bonusSuccess')
		{
			FGS.likeBonus(data, true);
			FGS.hideFromFeed(data, false);
			view.bonusSuccess(data, data2);
		}
		else if(msg == 'updateLike')
		{
			view.updateLike(data, data2);
		}
		else if(msg == 'updateComment')
		{
			view.updateComment(data, data2);
		}
		// bonusy off //


		// request //
		else if(msg == 'requestError')
		{
			view.requestError(data, data2);
		}
		else if(msg == 'requestSuccess')
		{
			if(typeof(data2.thanks) != 'undefined' && data2.thanks != '')
			{
				FGS.sendbackGift(data, data2.thanks);
			}
			view.requestSuccess(data, data2);
		}
		
		else if(msg == 'updateNeighbors')
		{
			view.neighborsLoaded(data, data2);
		}
		
		else if(msg == 'errorWithSend')
		{
			if(data2 != '')
			{
				view.updateSendback(data2, false, (typeof(data3) == 'undefined' ? false : true));
			}
			else
			{
				view.freegiftError(data);
			}
		}		
		else if(msg == 'freegiftSuccess')
		{
			if(typeof(data.friendID) != 'undefined')
			{
				FGS.database.addStats('giftSent', data.friendID+'_'+data.gameID, {time: Math.round(new Date().getTime() / 1000), count: 1});
			}
			if(data2 != '')
			{
				view.updateSendback(data2, true);
			}
			view.freegiftSuccess(data, data2);
		}	
		
		else if(msg == 'addNewBonus')
		{
			view.addNewBonus(data3);
		}
		else if(msg == 'addNewRequest')
		{
			view.addNewRequest(data3);
		}
		
		else if(msg == 'hiddenFeed')
		{
			view.hiddenFeed(data);
		}
		
		else if(msg == 'refresh')
		{
			view.location.reload();
		}
	}
};

FGS.loadOptions = function(userID)
{
	var stmt = FGS.database.db.createStatement("SELECT option FROM options where id = :id");
	stmt.params.id = 1;
	
	var results = [];

	while (stmt.executeStep())
	{
		results.push(stmt.row.option);
	}
	stmt.reset();

	if(results.length == 0)
	{
		FGS.options = FGS.jQuery.extend(true,{}, FGS.defaultOptions);
	}
	else
	{
		FGS.options = FGS.jQuery.extend(true,{}, FGS.defaultOptions,	JSON.parse(results[0]));
	}
	
	FGS.optionsLoaded = true;
	FGS.saveOptions();
	FGS.finishStartup();
};

FGS.saveOptions = function(callback)
{
	if(FGS.userID != null)
	{
		var opt = JSON.stringify(FGS.jQuery.extend(true,{},FGS.options));
		
		if(opt == '{}')
		{
			if(callback)
			{
				FGS.stopAll(true);
				callback();
			}
			return;
		}
		
		var stmt = FGS.database.db.createStatement("UPDATE options SET option = :option where id = :id");
		stmt.params.option = opt;
		stmt.params.id = 1;
		stmt.execute();
		
		if(callback)
		{
			FGS.stopAll(true);
			callback();
		}
	}
};

FGS.updateIcon = function()
{
	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	while (browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().document;
		var icon = bE.getElementById("fgs-toolbar-button");
		
		if(FGS.FBloginError === false)
		{
			FGS.jQuery(icon).addClass('fgs-toolbar-color');
			FGS.jQuery(icon).attr('popup', 'fgs-context-menu-loaded');
			FGS.jQuery(icon).attr('value', FGS.newElements);
			FGS.jQuery(icon).attr('tooltiptext', 'FGS: Click to open bonuses and gifts list');
			var tmp = bE.getElementById('fgs-context-menu-open-giftlist');
			FGS.jQuery(tmp).attr('label', 'Open giftlist ('+FGS.newElements+')');
			
			if(FGS.newElements == 0)
			{				
				FGS.jQuery(icon).addClass('fgs-toolbar-button-no-text');
			}
			else
			{
				FGS.jQuery(icon).removeClass('fgs-toolbar-button-no-text');
			}
		}
		else if(FGS.FBloginError === null)
		{
			FGS.jQuery(icon).removeClass('fgs-toolbar-color');
			FGS.jQuery(icon).attr('popup', 'fgs-context-menu-wait');
			FGS.jQuery(icon).attr('value', 'wait');
			FGS.jQuery(icon).attr('tooltiptext', 'FGS is not yet loaded... Please wait...');
		}
		else
		{
			FGS.jQuery(icon).removeClass('fgs-toolbar-color');
			FGS.jQuery(icon).attr('popup', 'fgs-context-menu-login');
			FGS.jQuery(icon).attr('value', 'x');
			FGS.jQuery(icon).addClass('fgs-toolbar-button-no-text');
			FGS.jQuery(icon).attr('tooltiptext', 'FGS: Click to login to Facebook');
		}
	}
};

FGS.openGiftList = function()
{
	FGS.alreadyOpened = true;
	
	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	var found = false;
	
	var tmpUrl = 'chrome://fgs/content/giftlist.html';
	
	while (!found && browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);
			if (tmpUrl == b.currentURI.spec)
			{
				bE.selectedTab = bE.tabContainer.childNodes[i];
				bE.focus();
				found = true;
				break;
			}
		}
	}
	
	if(!found)
	{
		var recentWindow = wm.getMostRecentWindow("navigator:browser");
	
		if (recentWindow) 
		{
			if(gBrowser.selectedBrowser.currentURI.spec == 'about:blank')
			{
				gBrowser.selectedBrowser.loadURI(tmpUrl);
			}
			else
			{
				recentWindow.delayedOpenTab(tmpUrl, null, null, null, null);
			}
		}
		else
		{
			window.open(tmpUrl);
		}
	}
};

FGS.openFacebook = function()
{
	var url = "https://www.facebook.com/login.php";

	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	while (browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);
			if (url == b.currentURI.spec)
			{
				bE.selectedTab = bE.tabContainer.childNodes[i];
				bE.focus();
				return false;
			}
		}
	}
	gBrowser.selectedTab = gBrowser.addTab(url);
};

FGS.checkVersion = function()
{
	Components.utils.import("resource://gre/modules/AddonManager.jsm");
	AddonManager.getAddonByID("friendlygamingsimplifier@flies", function(addon) 
	{
		FGS.currentVersion = addon.version;
	});
};

FGS.loadTranslations = function()
{
	for(var loc in FGS.transObj)
	{
		var req = new XMLHttpRequest();
		req.open("GET", "chrome://fgs/content/locales/"+loc+"/messages.json", false);
		req.overrideMimeType("text/plain");
		req.onreadystatechange = function()
		{
			if (req.readyState == 4)
			{
				var lang = req.responseText;
				
				try
				{
					var lang = JSON.parse(lang);
				}
				catch(e)
				{
					FGS.dump(e);
				}
				
				if(typeof FGS.translations[loc] == 'undefined')
				{
					FGS.translations[loc] = lang;
				}
			}
		}
		req.send(null);
		req = null;
	}
};

FGS.preStartup = function(e) 
{
	FGSlistener.onLoad();
	
	FGS.loadLibraries();
	
	FGS.jQuery.ajaxSetup({
		timeout: 120000,
		beforeSend: function(a, b) {
			if(b.url.indexOf('gifts.php&') != -1)
			{
				b.url = b.url.replace('gifts.php&', 'gifts.php?');
			}
		}
	});
	
	checkFGSoperator();
	
	var document = e.originalTarget;
	
	FGS.loadTranslations();
	
	FGS.checkVersion();

	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	var found = false;
	
	while (!found && browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext();
		if(bE.FGScheck != undefined)
		{
			found = bE;
			break;
		}
	}

	if(!found)
	{
		FGScheck = true;
	}
	else
	{
		FGS = found.FGS;
		FGS.updateIcon();
		return;
	}
	
	FGS.prepareIcon();		
	FGS.initializeDefaults();
	FGS.startup();
};

FGS.loadSubmenu = function(context)
{	
	(function(loader)
	{
		loader.loadSubScript("chrome://fgs/content/scripts/submenu.js");
	})
	(
		Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
					.getService(Components.interfaces.mozIJSSubScriptLoader)
	);
};

FGS.loadLibraries = function(context)
{
	(function(loader)
	{
		loader.loadSubScript("chrome://fgs/content/scripts/jquery-1.5.2.min.js");
		loader.loadSubScript("chrome://fgs/content/scripts/jquery.utils.js");
		loader.loadSubScript("chrome://fgs/content/scripts/jquery.base64.decode.js");
		loader.loadSubScript("chrome://fgs/content/scripts/buttonsAndFilters.js");
		loader.loadSubScript("chrome://fgs/content/browser_files/database.js");
		loader.loadSubScript("chrome://fgs/content/scripts/gifts.js");
		
		var arr = [];
		for(var ids in FGS.gamesData)
		{
			FGS[FGS.gamesData[ids].systemName] = {};
			
			try
			{
				loader.loadSubScript("chrome://fgs/content/scripts/games/"+FGS.gamesData[ids].systemName+".js");
				
				if(typeof(FGS[FGS.gamesData[ids].systemName+'Bonuses']) != 'undefined')
				{
					arr.push(FGS.gamesData[ids].systemName+' bonus');
				}
				if(typeof(FGS[FGS.gamesData[ids].systemName+'Requests']) != 'undefined')
				{
					arr.push(FGS.gamesData[ids].systemName+' request');
				}
			}
			catch(e)
			{
				//dump(FGS.gamesData[ids].systemName);
			}
		}
		
		//dump(arr.sort());
	})
	(
		Components.classes["@mozilla.org/moz/jssubscript-loader;1"]
					.getService(Components.interfaces.mozIJSSubScriptLoader)
	);

	var jQuery = window.jQuery.noConflict(true);
	if( typeof(jQuery.fn._init) == 'undefined') { jQuery.fn._init = jQuery.fn.init; }
	FGS.jQuery = jQuery;
};

FGS.prepareIcon = function()
{

	try 
	{
		var toolbar = document.getElementById("nav-bar");
		var curSet = toolbar.currentSet;
		if (curSet.indexOf("fgs-toolbar-button") == -1)
		{
			var set;
			if (curSet.indexOf("search-container") != -1)
				set = curSet.replace(/search-container/, "fgs-toolbar-button,search-container");
			else
				set = curSet + ",fgs-toolbar-button";
			toolbar.setAttribute("currentset", set);
			toolbar.currentSet = set;
			document.persist("nav-bar", "currentset");
			try
			{
				BrowserToolboxCustomizeDone(true);
			}
			catch (e){ }
		}
	}
	catch(e) { }
};

FGS.checkIfFacebookPage = function(e)
{
	try
	{
		var doc = e.originalTarget;
		var currentPageURI = doc.location.href;

		if(typeof(currentPageURI) == 'undefined' || currentPageURI == '')
			return false;
		
		if(currentPageURI.indexOf('.facebook.com/') == -1)	return;
		
		var topFrame = FGS.jQuery.trim(doc.defaultView.top.location.toString());
		var botFrame = FGS.jQuery.trim(doc.defaultView.self.location.toString());
		
		
		var testReg = new RegExp("facebook.com\/addfriend\.php(.+)id=(.*)\&fromFGS=(.*)");

		if(currentPageURI.match(testReg) && topFrame == botFrame)
		{
			var el = doc.getElementById('message');
			el.value = 'I found you by FGS ( http://fgs.rzadki.eu ). You stated that you are looking for neighbors in: '+FGS.Gup('fromFGS', currentPageURI);
			return;
		}		
		
		if(currentPageURI.indexOf('.facebook.com/') != -1 && topFrame == botFrame)
		{
			if(FGS.jQuery("#logout_form", doc).length > 0)
			{
				FGS.loginStatusChanged(true, doc.body.parentNode.innerHTML);
			}
			else if(FGS.jQuery("#login_form", doc).length > 0)
			{
				FGS.loginStatusChanged(false);
			}
			else
			{
				if(currentPageURI == 'http://www.facebook.com/ajax/ufi/modify.php?x=y' || currentPageURI == 'https://www.facebook.com/ajax/ufi/modify.php?x=y')
				{
					FGSoperator.port = doc;
					FGSoperator.port.postMessage = function(obj) {
					
						if(typeof obj.arguments.url != 'undefined')
						{
							FGS.jQuery.ajax({
								type: obj.arguments.type,
								url: obj.arguments.url,
								data: obj.arguments.data,
								dataType: 'text',
								success: function(d) {
									obj.response = {
										success: true,
										data: d
									};
									FGS.processOperatorMessage(obj);
								},
								error: function() {
									obj.response = {
										success: false,
										data: ''
									};
									FGS.processOperatorMessage(obj);
								}
							});
						}
					}
				}
			}
		}
	}
	catch(e)
	{
		FGS.dump(e);
	}
};

FGS.openRecovery = function()
{
	FGS.sendView('close');
	
	var url = 'chrome://fgs/content/recovery.html';

	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	var found = false;
	
	while (browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);
			if (url == b.currentURI.spec)
			{
				bE.selectedTab = bE.tabContainer.childNodes[i];
				bE.focus();
				found = true;
				return false;
			}
		}
	}
	
	if(!found)
	{
		var tmpUrl = url;
		var recentWindow = wm.getMostRecentWindow("navigator:browser");
	
		if (recentWindow) 
		{
			if(gBrowser.selectedBrowser.currentURI.spec == 'about:blank')
			{
				gBrowser.selectedBrowser.loadURI(tmpUrl);
			}
			else
			{
				recentWindow.delayedOpenTab(tmpUrl, null, null, null, null);
			}
		}
		else
		{
			window.open(tmpUrl);
		}
	}
};

FGS.findGameTab = function(url, callback, params) {

	var found = false;
	
	var args = [];
	for(var i=0; i<params.length; i++)
	{
		if(params[i] == null)
			params[i] = undefined;
		
		args.push('params['+i+']');
	}
	
	
	var wm = Components.classes['@mozilla.org/appshell/window-mediator;1']
			.getService(Components.interfaces.nsIWindowMediator);
	var browserEnumerator = wm.getEnumerator("navigator:browser");
	
	var found = false;
	
	while (browserEnumerator.hasMoreElements())
	{
		var bE = browserEnumerator.getNext().getBrowser();
		
		for (var i = 0; i < bE.browsers.length; i++)
		{
			var b = bE.getBrowserAtIndex(i);
			
			if (b.currentURI.spec.indexOf(url) != -1)
			{
				args.push('b');
				eval('callback('+args.join(',')+')');
				return false;
			}
		}
	}
	
	if(!found)
	{
		FGS.endWithError('other', 'bonus', params[1], 'Read notice above bonuses.');
		return;
	}
};

FGS.sendRequestToTab = function(tab, obj2)
{
	var doc = tab.contentDocument;
	
	if(typeof doc.processFGSmessage == 'undefined')
	{
		doc.processFGSmessage = function(obj)
		{	
			if(typeof obj.arguments.url != 'undefined')
			{
				FGS.jQuery.ajax({
					type: obj.arguments.type,
					url: obj.arguments.url,
					data: obj.arguments.data,
					dataType: 'text',
					beforeSend: function( xhr ) 
					{
						xhr.setRequestHeader('Referer', obj.arguments.referer);  
					},
					success: function(d) {
						obj.response = {
							success: true,
							data: d
						};
						FGS.dump(d);
						FGS.processOperatorMessage(obj);
					},
					error: function() {
						obj.response = {
							success: false,
							data: ''
						};
						FGS.processOperatorMessage(obj);
					}
				});
			}
		};
	}
	doc.processFGSmessage(obj2);
};

FGS.dump = function(msg)
{
	if(FGSdebugMode)
	{
		var cs = Components.classes["@mozilla.org/consoleservice;1"]
                     .getService(Components.interfaces.nsIConsoleService);
		cs.logStringMessage(msg);
	}
};